# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.core.paginator import Paginator
from myhomework.account.daos import *
from myhomework.account.forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login

#@require_perm(perm='group.member')
from myhomework.exceptions.exception import *
from myhomework.account.decorators import *
from myhomework.common.decorators import *
from django.template import RequestContext
class UserView(object):
    
    #accountviews
    @staticmethod
    def login_view(request,context={},login_template='login.html'):
        
        username = request.POST.get('username')
        password = request.POST.get('password')
        if(not username or not password):
            return render_to_response(login_template,context, context_instance=RequestContext(request))
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return HttpResponseRedirect('/index')
        else:
            raise LoginError(user)


    @staticmethod
    @process_exception
    def create_user(request,context={}):
        if request.method == 'POST':          
            form = CreateUserForm(request.POST)
            if form.is_valid():
                user = form.save(commit=False)
                UserDao.add_user(user)
                return HttpResponse('{}')
            else:
                raise UserDataFormError(form.errors)
        
        return render_to_response('ajax/register.html',context, context_instance=RequestContext(request))

        
    @staticmethod
    def manage_user(request,context={}):
        return render_to_response('ajax/user_list.html',context, context_instance=RequestContext(request))
    
    @staticmethod
    def user_list_content(request,context={}):
        start_s = request.GET.get('start')
        limit_s = request.GET.get('limit')
        
        try:
            start = int(start_s)
        except:
            start = 0
        try:
            limit = int(limit_s)
        except:
            limit = 10
            
        type = request.GET.get('type')
        if(type=='active'):
            users = UserDao.get_active_user_list(start=start,limit=limit)
        elif(type=='unactive'):
            users = UserDao.get_not_active_user_list(start=start,limit=limit)
        else:
            users = UserDao.get_user_list(start=start,limit=limit)
        context.update({'users':users})
        return render_to_response('ajax/user_list_content.html',context, context_instance=RequestContext(request))
    
    @staticmethod
    def user_count(request,context={}):
        #count = GroupDao.get_number_of_group()c
        if(type=='active'):
            count = UserDao.get_number_of_active_user()
        elif(type=='unactive'):
            count = UserDao.get_number_of_not_active_user()
        else:
            count = UserDao.get_number_of_user()
        return HttpResponse('{"count":"%d"}'%(count,), mimetype="text/plain")
        
    @staticmethod
    def logout_view(request,context={},login_template='login.html'):
        username = request.POST.get('username')
        password = request.POST.get('password')
        if(not username or not password):
            return render_to_response(login_template,context, context_instance=RequestContext(request))
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect('/index')
        else:
            raise LoginError(user)
        
    @staticmethod
    @process_exception
    def delete_user(request,context={}):
        user = request.GET.get('user')
        UserDao.delete_user(user)
        return HttpResponse('{}')
        
    @staticmethod
    @process_exception
    def pass_user(request,context={}):
        user = request.GET.get('user')
        UserDao.pass_user(user)
        return HttpResponse('{}')
    
    @staticmethod
    @process_exception
    @login_required
    @user_profile
    def edit_info(request,context={}):
        if request.method == 'POST':          
            form = EditUserForm(request.POST)
            if form.is_valid():
                user = form.save(commit=False)
                user.id = request.user.user.id
                user.group = request.user.user.group
                user.auth_user = request.user
                user.student_id=request.user.username
                user.last_updated_time = request.user.user.last_updated_time
                user.save()
                return HttpResponse('{}')
            else:
                raise UserDataFormError(form.errors)
        return render_to_response('ajax/edit_info.html',context, context_instance=RequestContext(request))
    
    @staticmethod
    @process_exception
    @login_required
    @user_profile
    def edit_password(request,context={}):
        if request.method == 'POST':          
            form = EditPasswordFrom(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                UserDao.user_set_password(request.user.username,cd['old_password'],cd['new_password'],cd['new_password'])
                return HttpResponse('{}')
            else:
                raise UserDataFormError(form.errors)
        return render_to_response('ajax/edit_password.html',context, context_instance=RequestContext(request))
      
    @staticmethod
    @process_exception
    def set_user_TA(request,context={}):
        user_id = request.GET.get('user')
        UserDao.set_user_TA(user_id)
        
        return HttpResponse('{}')
    
    @staticmethod
    @process_exception
    def remove_user_TA(request,context={}):
        user_id = request.GET.get('user')
        UserDao.remove_user_TA(user_id)
        
        return HttpResponse('{}')
    
    
    
class GroupView(object):
    
    @staticmethod
    @login_required
    @user_profile
    def index(request,context={}):
        return render_to_response('index.html',context, context_instance=RequestContext(request))
    
    #@require_perm('group.member')
    
    @staticmethod
    @login_required
    @user_profile
    def my_group(request,context={}):
        if(request.user.user.group):#user has joined in group
            return render_to_response('ajax/my_group.html',context, context_instance=RequestContext(request))
        else:#user has not joined in group
            return HttpResponseRedirect('create_group')
    
    #show the page of group list
    @staticmethod
    @login_required
    @user_profile
    def group_list(request,context={}):
        return render_to_response('ajax/group_list.html',context, context_instance=RequestContext(request))
    
    #response a list of groups
    @staticmethod
    @login_required
    @user_profile
    def group_list_content(request,context={}):
        
        start_s = request.GET.get('start')
        limit_s = request.GET.get('limit')
        
        try:
            start = int(start_s)
        except:
            start = 0
        
        try:
            limit = int(limit_s)
        except:
            limit = 10
            
        #print start
        #print limit
        
        output_group_list = GroupDao.get_group_list(start=start,limit=limit)

        #print output_group_list
        
        
        #for  group in output_group_list : 
        #      print group.administrator
              
        context.update({'group_list':output_group_list})
        
    
        return render_to_response('ajax/group_list_content.html',context, context_instance=RequestContext(request))
    
    @staticmethod
    def group_count(request,context={}):
        count = GroupDao.get_number_of_group()
        return HttpResponse('{"count":"%d"}'%(count,), mimetype="text/plain")
    
    @staticmethod
    @process_exception
    @need_settings('allow_create_group')
    def create_group(request,context={}):
        print "ok2!!!!"
        print request.method
        if request.method == 'POST':
            
            form = CreateGroupForm(request.POST,)
            if form.is_valid():
                group = form.save(commit=False)
                print group
                GroupDao.create_group(group,request.user.username)
                return HttpResponse('{}')
            print 'ok4!!'
            print form.errors
        print "ok3!!!!"
        return render_to_response('ajax/create_group.html',context, context_instance=RequestContext(request))
    
    @staticmethod
    @process_exception
    def user_join_group(request, context={}):
        
        student_id = request.user.username
        group_id = request.GET.get('group')
        
        GroupDao.join_group(group_id, student_id)
        
        return HttpResponse('{}')
    
    @staticmethod
    @process_exception
    def user_quit_group(request, context={}):
        
        student_id = request.user.username
        group_id = request.GET.get('group')
        print group_id
        GroupDao.quit_group(group_id, student_id)
        
        return HttpResponse('{}')
    
    @staticmethod
    @process_exception
    def delete_group(request, context={}):
        
        group_id = request.GET.get('group')
        
        GroupDao.delete_group(group_id)
        
        return HttpResponse('{}')
    
    
    """
    2011.5.19 afternoon modify
    """
    #only administrator can do that
    @staticmethod
    @process_exception
    def admin_quit_user_from_group(request, context={}):
        
        group_id = request.GET.get('group')
        student_id = request.GET.get('user')
        
        GroupDao.quit_group(group_id, student_id)
        
        return HttpResponse('{}')
    
    #only administrator can do that
    @staticmethod
    @process_exception
    def change_group_administrator(request, context={}):
        
        group_id = request.GET.get('group')
        print group_id
        student_id = request.GET.get('user')
        
        GroupDao.change_group_administrator(group_id, student_id)
        
        return HttpResponse('{}')
    
    @staticmethod
    @process_exception
    def edit_group_name(request, context={}):
         
        group_id = request.GET.get('group')
        new_name = request.GET.get('new_name')
        
        GroupDao.edit_group_name(group_id, new_name)
        
        return HttpResponse('{}')
    
    # Create your views here.
    
        